﻿/*
* 创建者：LIYINFAI
* 创建时间：2023/10/24 9:35:26
* 描述：
* --------------------------------------
* 修改说明：
* --------------------------------------
*/
using SQLiteEx;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace CommonLibrary
{
    /// <summary>
    /// 用户表
    /// </summary>
    [Table("users")]
    public class UserInfo
    {
        /// <summary>
        /// Id
        /// </summary>
        [PrimaryKey]
        [AutoIncrement]
        [Description("Id")]
        public long Id { get; set; }
        /// <summary>
        /// 员工编号
        /// </summary>
        [Description("员工编号")]
        public string YGBH { get; set; }
        /// <summary>
        /// 用户名
        /// </summary>
        [Description("用户名")]
        public string UserName { get; set; }
        /// <summary>
        /// UserPassword
        /// </summary>
        [Description("用户密码")]
        public string UserPassword { get; set; }
        /// <summary>
        /// 姓名
        /// </summary>
        [Description("姓名")]
        public string Name { get; set; }
        /// <summary>
        /// 权限
        /// </summary>
        [Description("权限")]
        public int Permission { get; set; }
        /// <summary>
        /// 创建时间
        /// </summary>
        [Description("创建时间")]
        public string Created { get; set; }
        /// <summary>
        /// 登录状态
        /// </summary>
        [Description("登录状态")]
        public int Status { get; set; }
        /// <summary>
        /// 上次登录时间
        /// </summary>
        [Description("上次登录时间")]
        public string LoginTime { get; set; }
        /// <summary>
        /// 上次注销时间
        /// </summary>
        [Description("上次注销时间")]
        public string LogoutTime { get; set; }
        /// <summary>
        /// 刷卡号码
        /// </summary>
        [Description("刷卡号码")]
        public string CreditCardID { get; set; }
        /// <summary>
        /// 描述信息
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return CommonHelper.GetObjectString(this);
        }
    }

    /// <summary>
    /// 用户数据库操作类
    /// </summary>
    public class UserSQLiteDb : SQLiteHelper
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbPath"></param>
        public UserSQLiteDb(string dbPath) : base(dbPath)
        {
        }
        /// <summary>
        /// 单例对象
        /// </summary>
        /// <returns></returns>
        public static UserSQLiteDb Instance()
        {
            string dbFile = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dbs"), $"users.db");
            CommonHelper.CheckDirectory(dbFile);
            UserSQLiteDb db = null;
            if (CommonHelper.CheckFile(dbFile))
            {
                db = new UserSQLiteDb(dbFile);
                db.CreateTable<UserInfo>();
                db.Insert(new UserInfo()
                {
                    UserName = "Admin",
                    UserPassword = EncryptDecryptHelper.Encrypt("1"),
                    Permission = 4,
                    Created = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    Name = "超级管理员",
                    Status = 1,
                    YGBH = "0001"
                });
            }
            else
            {
                db = new UserSQLiteDb(dbFile);
            }
            return db;
        }
    }
    /// <summary>
    /// 用户资料帮助类
    /// </summary>
    public class UserHelper
    {
        /// <summary>
        /// 当前用户
        /// </summary>
        private static UserInfo _loginUser = null;
        /// <summary>
        /// 获取当前用户
        /// </summary>
        public static UserInfo LoginUser
        {
            get
            {
                return _loginUser;
            }
        }
        /// <summary>
        /// 权限检测
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="minPermission"></param>
        /// <returns></returns>
        public static bool CheckPermission(IWin32Window owner, int minPermission)
        {
            bool result = false;
            if (LoginUser == null || LoginUser.Permission < minPermission && minPermission == 1)
            {
                HWMessageBox.Show(owner, "无权限操作");
            }
            else if (LoginUser == null || LoginUser.Permission < minPermission && minPermission == 2)
            {
                HWMessageBox.Show(owner, "无权限操作");
            }
            else if (LoginUser == null || LoginUser.Permission < minPermission && minPermission == 3)
            {
                HWMessageBox.Show(owner, "需要工程师级别以上权限");
            }
            else if (LoginUser == null || LoginUser.Permission < minPermission && minPermission == 4)
            {
                HWMessageBox.Show(owner, "需要管理员级别");
            }
            else
            {
                result = true;
            }
            return result;
        }
        /// <summary>
        /// 增加用户
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public static bool AddUser(UserInfo userInfo)
        {
            bool result = false;
            using (UserSQLiteDb db = UserSQLiteDb.Instance())
            {
                var user = db.Insert(userInfo);
                result = user > 0;
                LogHelper.Debug($"【{UserHelper.LoginUser}】新增用户：{userInfo}，结果：{result}");
            }
            return result;
        }
        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public static bool EditUser(UserInfo userInfo)
        {
            bool result = false;
            using (UserSQLiteDb db = UserSQLiteDb.Instance())
            {
                var user = db.ToList<UserInfo>($"select * from users where Id={userInfo.Id}").FirstOrDefault();
                if (user != null && user.Id.Equals(userInfo.Id))
                {
                    user.UserPassword = userInfo.UserPassword;
                    user.Permission = userInfo.Permission;
                    user.Name = userInfo.Name;
                    user.CreditCardID = userInfo.CreditCardID;
                    result = db.Update(user) > 0;
                    LogHelper.Debug($"【{UserHelper.LoginUser}】编辑用户，修改前：{user}，修改后：{userInfo}，结果：{result}");
                }
            }
            return true;
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool DeleteUser(long id)
        {
            bool result = false;
            using (UserSQLiteDb db = UserSQLiteDb.Instance())
            {
                var user = db.ToList<UserInfo>($"select * from users where Id={id}").FirstOrDefault();

                if (user != null && user.Id > 0)
                {
                    result = db.Delete(user) > 0;
                    LogHelper.Debug($"【{UserHelper.LoginUser}】删除用户：{user}，结果：{result}");
                }
            }
            return true;
        }
        /// <summary>
        /// 获取所有用户资料
        /// </summary>
        /// <returns></returns>
        public static List<UserInfo> GetAllUsers()
        {
            List<UserInfo> users = new List<UserInfo>();
            using (UserSQLiteDb db = UserSQLiteDb.Instance())
            {
                users = db.ToList<UserInfo>($"select * from users where Permission<={LoginUser.Permission}");
            }
            return users;
        }
        /// <summary>
        /// 用户登陆
        /// </summary>
        /// <param name="loginType"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="cardNo"></param>
        /// <returns></returns>
        public static UserInfo UserLogin(ELoginType loginType, string userName, string password, string cardNo)
        {
            UserInfo user = loginType == ELoginType.USERNAME ? GetUserByUserNamePassword(userName, password) :
                GetUserByCardNo(cardNo);
            if (user != null && user.Id > 0)
            {
                _loginUser = user;
            }
            return user;
        }
        /// <summary>
        /// 获取用户资料
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password">加密后</param>
        /// <returns></returns>
        private static UserInfo GetUserByUserNamePassword(string userName, string password)
        {
            UserInfo userInfo = null;
            if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
            {
                using (UserSQLiteDb db = UserSQLiteDb.Instance())
                {
                    userInfo = db.ToList<UserInfo>($"select * from users where UserName='{userName}' and UserPassword='{password}'").FirstOrDefault();
                }
            }
            return userInfo;
        }
        /// <summary>
        /// 获取用户资料
        /// </summary>
        /// <param name="cardNo">加密后</param>
        /// <returns></returns>
        private static UserInfo GetUserByCardNo(string cardNo)
        {
            UserInfo userInfo = null;
            if (!string.IsNullOrWhiteSpace(cardNo))
            {
                using (UserSQLiteDb db = UserSQLiteDb.Instance())
                {
                    userInfo = db.ToList<UserInfo>($"select * from users where CreditCardID='{cardNo}'").FirstOrDefault();
                }
            }
            return userInfo;
        }
        /// <summary>
        /// 注销
        /// </summary>
        public static void Logout()
        {
            if (_loginUser != null)
            {
                LogHelper.Info($"{_loginUser.Name},用户注销");
                _loginUser = null;
                if (APPInstance.IsPLCConnected)
                {
                    APPInstance.PLC.Write(AppPLCSetting.Instance().IsLogout, (short)1);//注销
                }
            }
        }
    }
}
